package com.yonyou.distribute.service;

import com.yonyou.distribute.lock.DistributedLockClient;
import com.yonyou.distribute.lock.DistributedRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * p33--p36
 * 分布式锁---可重入
 */
@Slf4j
@Service
public class RedisService_5 {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    private DistributedLockClient distributedLockClient;

    @Transactional
    public void deduct() {
        DistributedRedisLock redisLock = this.distributedLockClient.getRedisLock("lock");
        redisLock.lock();
        try {
            // 1、查询库存
            String stock = stringRedisTemplate.opsForValue().get("stock").toString();
            // 2、判断库存是否充足
            if(!StringUtils.isEmpty(stock)){
                Integer st = Integer.valueOf(stock);
                if(st > 0){
                    //3、更新库存到数据库
                    stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
                }
            }
            this.test();
        } finally {
            redisLock.unlock();
        }
    }

    /**
     * 测试可重入锁
     */
    public void test() {
        DistributedRedisLock lock = this.distributedLockClient.getRedisLock("lock");
        lock.lock();
        System.out.println("可重入....");
        lock.unlock();
    }
}
